package com.iraeta.service.basic.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.common.ServiceException;
import com.iraeta.dao.bpm.HrYgkqjlcDao;
import com.iraeta.dao.bpm.HrYgkqjlmDao;
import com.iraeta.dao.main.KaoqinyuanDao;
import com.iraeta.dao.main.sys.UserDao;
import com.iraeta.entity.bpm.HrYgkqjlc;
import com.iraeta.entity.bpm.HrYgkqjlm;
import com.iraeta.entity.main.Kaoqinyuan;
import com.iraeta.entity.main.User;
import com.iraeta.service.basic.KaoQinService;
import com.iraeta.service.sys.impl.WeiXinService;
import com.iraeta.uitl.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class KaoQinServiceImpl implements KaoQinService {
    private static final Logger logger = LoggerFactory.getLogger(KaoQinServiceImpl.class);

    @Lazy
    @Autowired
    KaoQinService that;
    @Autowired
    HrYgkqjlmDao mDao;
    @Autowired
    HrYgkqjlcDao cDao;
    @Autowired
    WeiXinService weiXinService;
    @Autowired
    KaoqinyuanDao kaoqinyuanDao;
    @Autowired
    UserDao userDao;

    @Override
    public void processWeiXinKaoQinEveryDay() {
        Date prevDay = DateUtil.offsetDay(DateUtil.parseDate(DateUtil.today()), -1);
        List<Kaoqinyuan> kaoqinyuanList = kaoqinyuanDao.selectAll();
        for (Kaoqinyuan kaoqinyuan : kaoqinyuanList) {
            try {
                that.processKaoQinYuanEveryDay(kaoqinyuan, prevDay);
            }catch (Exception e){
                logger.error(kaoqinyuan.getCmaker() + "-" + DateUtil.format(prevDay, "YYYY-MM-dd") + "同步异常:" + e.getMessage());
            }
        }
    }

    @Override
    public void processKaoQinYuanEveryDay(Kaoqinyuan kaoqinyuan, Date prevDay) {
        String cmaker = mDao.selectByDayAndMakerNo(kaoqinyuan.getCmakerno(), DateUtil.format(prevDay, "YYYY-MM-dd"));
        if(cmaker != null){ //本天已经填报过
            return;
        }
        List<User> userList = userDao.selectUserByKqy(String.valueOf(kaoqinyuan.getId()));
        List<String> users = userList.stream().map(User::getWxuid).collect(Collectors.toList());
        JSONObject jb = weiXinService.getWeiXinKaoQin(users, prevDay);

        JSONArray jbData = jb.getJSONArray("datas");
        List<HrYgkqjlc> hrYgkqjlcList = new ArrayList<>();
        List<String> exceptionUserNameList = new ArrayList<>();
        for(int i = 0;i<jbData.size();i++){
            JSONObject ryJSONObject = jbData.getJSONObject(i);
            JSONObject baseJSONObject = ryJSONObject.getJSONObject("base_info");
            JSONArray exceptionJSONArray = ryJSONObject.getJSONArray("exception_infos");
            JSONObject summaryJSONObject = ryJSONObject.getJSONObject("summary_info");
            String wxId = baseJSONObject.getString("acctid");
            User user = userDao.selectByWxuid(wxId);
            if(user == null){
                continue;
            }
            boolean isException = false;
            int record_type = baseJSONObject.getInteger("record_type");
            if(record_type != 1 && record_type != 2){   //如果不是固定上下班打卡 或者外出打卡
                isException = true;
            }else {
                int checkin_count = summaryJSONObject.getInteger("checkin_count");
                if(checkin_count != 4){ //打卡次数
                    isException = true;
                }else{
                    if(exceptionJSONArray.size() > 0){
                        isException = true;
                    }
                }
            }
            HashMap<String, Object> dangAnMap = mDao.getDangAn(user.getCdefine1());
            HrYgkqjlc hrYgkqjlc = new HrYgkqjlc();  //子表
            hrYgkqjlc.setCygxm(dangAnMap.get("cygxm").toString());
            hrYgkqjlc.setCsfzh(dangAnMap.get("csfzh").toString());
            hrYgkqjlc.setCwcqjl(new BigDecimal("0"));
            hrYgkqjlc.setCrybh(user.getCdefine1());
            hrYgkqjlc.setCbm(dangAnMap.get("cgzbm").toString());
            hrYgkqjlc.setCbmbm(dangAnMap.get("cgzbmbm").toString());
            hrYgkqjlc.setCgzgw(dangAnMap.get("cgzgw").toString());
            if(!isException){
                hrYgkqjlc.setCkqjl(new BigDecimal("1.00"));
                hrYgkqjlc.setCwcqjl(new BigDecimal("0.00"));
                hrYgkqjlc.setCcqlx("全勤");
            }else {
                hrYgkqjlc.setCkqjl(new BigDecimal("0.00"));
                hrYgkqjlc.setCwcqjl(new BigDecimal("1.00"));
                hrYgkqjlc.setCcqlx("休班");
                exceptionUserNameList.add(user.getName());
            }
            hrYgkqjlcList.add(hrYgkqjlc);
        }

        HashMap<String, Object> iidParam = new HashMap<>();
        iidParam.put("key1", "hr_ygkqjlm"); //hr_ygkqjlm
        iidParam.put("key2", 0L);
        mDao.selectMaxIID(iidParam);
        if(iidParam.get("key2") == null){
            throw new ServiceException("获取IID失败");
        }
        Long newIID = (Long) iidParam.get("key2");
        String dayStr = DateUtil.format(prevDay, "YYYYMMdd");
        String cjldh = mDao.selectMaxcjldh("KQJL-" + dayStr);
        String newcjldh = null;
        if(cjldh == null){
            newcjldh = "KQJL-" + dayStr + "0001";
        }else {
            String cjldhSplit = cjldh.substring(("KQJL-" + dayStr).length());
            newcjldh = "KQJL-" + dayStr + Util.getNextNumber(cjldhSplit);
        }

        HrYgkqjlm hrYgkqjlm = new HrYgkqjlm();  //主表
        hrYgkqjlm.setCmaker(kaoqinyuan.getCmaker());
        hrYgkqjlm.setCmakerno(kaoqinyuan.getCmakerno());
        hrYgkqjlm.setCstate(null);
        hrYgkqjlm.setDdate(prevDay);
        hrYgkqjlm.setIdepid(Long.valueOf( kaoqinyuan.getIdeptid()));
        hrYgkqjlm.setCkqbm(kaoqinyuan.getCkqbm());
        hrYgkqjlm.setCkqbmbm(kaoqinyuan.getCkqbmbm());
        hrYgkqjlm.setCnote("企业微信自动同步");
        hrYgkqjlm.setCgw(kaoqinyuan.getCgw());
        hrYgkqjlm.setIid(newIID);
        hrYgkqjlm.setCcode("");
        hrYgkqjlm.setCjldh(newcjldh);
        for (HrYgkqjlc hrYgkqjlc : hrYgkqjlcList) {
            hrYgkqjlc.setIid(newIID);
            cDao.insert(hrYgkqjlc);
        }
        mDao.insert(hrYgkqjlm);

        //更新cCode字段
        HashMap<String, Object> codeParam = new HashMap<>();
        codeParam.put("key1", "hr_ygkqjl");
        codeParam.put("key2", newIID);
        codeParam.put("key3", "");
        mDao.selectMaxCCODE(codeParam);

        //发送消息
        if(exceptionUserNameList.size() > 0){
            String names = Util.parseListToString(exceptionUserNameList);
            String content = DateUtil.format(prevDay, "YYYY-MM-dd") + " [" + names+ "] 微信打卡异常,请确认并在bpm日考勤处理";
            String toUser = kaoqinyuan.getCdefine1();
            weiXinService.setWxUserTextMessage(toUser, content);
        }
    }
}
